'use strict';

const Controller = require('egg').Controller;

const { Op } = require("sequelize");

const {getSign} = require('./../../utils/intelligent-chatting')

class DictionaryController extends Controller {
  async index() {
    const { ctx, service } = this;
    const { Response, ResponseError, query } = ctx
    const res = new Response() //作为响应
    try {
      const { prefix, question } = query

      if(prefix === undefined || question === undefined) {
        throw new ResponseError('参数不符合要求')
      }

      const prefixModel = await service.prefix.findByPrefix(prefix)
      if(!prefixModel) {
        throw new ResponseError(prefix + '前缀无法识别')
      }

      const { id: prefix_id } = prefixModel //获取到前缀id

      //正则匹配
      const confition = {
        [Op.regexp]: `,?${prefix_id},?`
      }

      let dictionaries = await service.dictionary.findAll({
        where: { prefix_ids: confition, keyword: question },
        attributes: ['id', 'keyword', 'description', 'prefix_ids']
      })

      if(!dictionaries.length) {//数据库没有查询到
        const {data: {data}} = await ctx.curl('https://api.ai.qq.com/fcgi-bin/nlp/nlp_textchat', {
          // 必须指定 method
          method: 'POST',
          // 通过 contentType 告诉 HttpClient 以 JSON 格式发送
          contentType: 'application/x-www-form-urlencoded',
          data: getSign(question),
          // 明确告诉 HttpClient 以 JSON 格式处理返回的响应 body
          dataType: 'json',
        });
        const answer = data && data.answer
        dictionaries= [{id: '1', description: answer}]
      }

      res.data = {
        dictionaries
      }
    }catch(e) {
      res.status = ctx.STATUS.ERROR;
			res.message = e;
    }
    ctx.body = res
  }


  async create() {
    
  }
}

module.exports = DictionaryController;
